import { useEventsRegister } from "@/biz-components/hoc-form/with-list/use-events";
import React, { useEffect, useState } from "react";
import TableRender from "@/biz-components/table-render";
import { useMetaInit } from "../utils";
import { hocEvents } from "hoc-form";
import { withRouter } from 'umi';
import { toJS } from "@formily/reactive";

export interface WithTableProps {
  pageCode: string;
  loading: boolean;
  events?: hocEvents;
  rowKey?: string;
  pagination?: boolean;
  rowSelection?: any;
  [propsName: string]: any;
}

const WithTable: React.FC<WithTableProps> = (props) => {
  const {
    value,
    pagination = false,
    pageCode,
    rowsRender,
    editable = true,
    loading,
    events,
    cb,
    rowKey,
    match,
    history,
    data,
    validator,
    dynamicCols,
    ...extraProps
  } = props;
  const [configs, setConfigs] = useMetaInit(pageCode);
  const hookMapIns = React.useRef({
    tableButtonsEvents: {},
    buttonsEvents: {},
  });

  const { tableButtons, buttons, tableColumns } = configs;
  // 事件注册
  const { getTableTopButton, operations } = useEventsRegister(
    hookMapIns,
    events,
    {
      history,
      pageCode,
      callback: cb,
      tableButtons,
      buttons,
      loading,
      validator,
    }
  );

  let columns = tableColumns ? [...tableColumns] : [];
  if (dynamicCols && dynamicCols.length) {
    columns.push(...toJS(dynamicCols));
  }

  return (
    <TableRender
      rowKey={rowKey || "id"}
      metas={columns}
      pagination={pagination}
      data={{
        content: data || value || [],
        totalElements: 0,
        number: 0,
        size: 0,
      }}
      rowsRender={rowsRender}
      match={match}
      isRequesting={loading}
      operation={editable ? operations : ""}
      operAuths={tableButtons?.map(() => "")}
      extraAction={getTableTopButton()}
      {...extraProps}
    />
  );
};

// @ts-ignore
export default withRouter<WithTableProps>(WithTable);
